import markdown
from markdown.inlinepatterns import Pattern
from markdown.util import etree
import re

def makeReg(tag):
    return r'({)([^{}]+)}\('+re.escape(tag)+'\)'

num_arg_components = 0
argcomps = { 
    'premise': 0, 'data':0, 'warrant': 0, 'backing': 0, 
    'claim': 0, 'qualifier': 0, 'rebuttal': 0, 
    'counter-rebuttal': 0 }

class AttrTagPattern(Pattern):
    """
    Return element of type `tag` with a text attribute of group(3)
    of a Pattern and with the html attributes defined with the constructor.
    """
    def __init__(self, pattern, tag, attrs, child_tag):
        Pattern.__init__(self, pattern)
        self.tag = tag
        self.attrs = attrs
        self.child_tag = child_tag

    def handleMatch(self, m):
        global num_arg_components
        argcomps[self.child_tag] += 1
        elid = self.child_tag + str(argcomps[self.child_tag])

        el = etree.Element(self.tag)
        el.set('id',elid)

        el.text = m.group(3) + ' '
        for (key, val) in self.attrs.items():
            el.set(key, val)

        child = etree.SubElement(el, 'a')
        child.text = '(' + self.child_tag + ')'
        child.set('title', 'Counter this '+self.child_tag)
        child.set('href', 'counter/'+elid)
        child.set('class', 'debate_label')
        child.set('onmouseover', 'argcomp_select("'+elid+'")') # highlight the argument component span
        child.set('onmouseout', 'argcomp_unselect("'+elid+'")')

        return el


class DebateSyntaxExtension(markdown.Extension):
    def __addPattern( self, md, name, markdown_tag ):
        tag = AttrTagPattern(
            makeReg(markdown_tag), 'span', {'class':'argument_component'}, name)
        md.inlinePatterns.add(name, tag, '_end')

    def extendMarkdown(self, md, md_globals):
        self.__addPattern(md,'premise','p')
        self.__addPattern(md,'warrant','w')
        self.__addPattern(md,'backing','b')
        self.__addPattern(md,'claim','c')
        self.__addPattern(md,'qualifier','q')
        self.__addPattern(md,'rebuttal','r')
        self.__addPattern(md,'counter-rebuttal','cr')


def makeExtension(configs=None):
    return DebateSyntaxExtension(configs=configs)
